<template>
  <div class="safe_box">
    <tab title="安全中心"></tab>
    <div class="safe_cont">
      <ul>
        <li class="safe_item">
          <div class="safe_img">
              <i class="iconfont el-icon-knife-password iconsize"></i>
          </div>
          <div class="safe_infos">
            <h2>登录密码</h2>
            <h3>用于保护账号信息和安全登录</h3>
          </div>
          <div class="txt-rt">
            <el-button type="text" class="color-blue" @click="pwdDialogVisi = true">修改</el-button>
          </div>
        </li>
        <li class="safe_item">
          <div class="safe_img">
              <i class="el-icon-mobile-phone iconsize"></i>
          </div>
          <div class="safe_infos">
            <h2>手机安全</h2>
            <h3>可用于修改已绑定的手机号</h3>
          </div>
          <div class="txt-rt">
            <el-button type="text" class="color-blue" @click="showChangePhoneDia">修改</el-button>
          </div>
        </li>
      </ul>
    </div>
    <!-- pop -->
    <el-dialog  title="修改登录密码" :visible.sync="pwdDialogVisi" width="380px" :before-close="closePop" top="20vh" center>
      <p class="error" v-if="oldpwdError.status">{{oldpwdError.text}}</p>
      <el-form :model="modifyPwdForm" label-position="top" label-width="120px" ref="changePwd" :rules="changePwdrules"  style="text-align: left;">
        <el-form-item label="输入旧密码" prop="oldpwd">
          <el-input v-model="modifyPwdForm.oldpwd"  type="password" auto-complete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="设置新密码" prop="newpwd">
          <el-input v-model="modifyPwdForm.newpwd" type="password" auto-complete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="repwd">
          <el-input v-model="modifyPwdForm.repwd" type="password" auto-complete="off" clearable></el-input>
        </el-form-item>
        <el-form-item class="sureBtn">
          <el-button type="primary" style="width:100%" @click="modifyPwd('changePwd')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改手机号 -->
    <el-dialog  title="安全验证" :visible.sync="changePhoneVisi" width="380px" top="20vh" center>
      <!-- <template v-if="oldphoneTem"> -->
        <el-form status-icon label-position="top" label-width="120px" ref="phoneCode"  style="text-align: left;">
          <span>使用手机号</span> <span>{{mobile | phoneReplace}}</span>
          <!-- <el-form-item label="使用手机号" >
            <p>{{mobile | phoneReplace}}</p>
          </el-form-item> -->
          <el-form-item label="短信验证" >
            <el-input v-model="changePhoneForm.code" type="text" auto-complete="off" clearable>
              <div slot="append" class="valiCode">
                <el-button type="text" @click="getCode(mobile, 0)" :disabled="isSend" :class="{'disabled': isSend}">{{validateText}}</el-button>
              </div>
            </el-input>
          </el-form-item>
          <p class="error" v-if="oldMobError.status">{{oldMobError.text}}</p>
          <el-form-item label="图形验证码" >
            <el-input v-model="changePhoneForm.imgVerifyCode" type="text" auto-complete="off" clearable>
              <div slot="append" class="imgCode">
                <img v-show="codeImg" :src="codeImg" class="codeImg" @click="verifyImage"/>
              </div>
            </el-input>
          </el-form-item>
          <el-form-item class="sureBtn">
            <el-button type="primary" style="width:100%" @click="modifyPhoneOne">确定</el-button>
          </el-form-item>
        </el-form>
      <!-- </template> -->
    </el-dialog>
    <el-dialog  title="更换手机号码" :visible.sync="newPhoneVisi" width="380px" top="20vh" center>
      <!-- <template v-if="newPhoneVisi"> -->
        <el-form :model="newPhoneForm" status-icon label-position="top" label-width="120px" ref="newphone" :rules="newPhoneFormrules">
          <el-form-item label="新手机号码" prop="newtel">
            <el-input v-model="newPhoneForm.newtel"  type="text" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="图形验证码" prop="imgCode">
            <el-input v-model="newPhoneForm.imgVerifyCode" type="text" auto-complete="off" clearable>
              <div slot="append" class="valiCode">
                <img v-show="codeImg" :src="codeImg" class="codeImg" @click="verifyImage"/>
              </div>
            </el-input>
          </el-form-item>
          <el-form-item label="短信验证" prop="code">
            <el-input v-model="newPhoneForm.code" type="text" auto-complete="off" clearable>
              <div slot="append" class="valiCode">
                <el-button type="text" @click="getCode(newPhoneForm.newtel, 0)" :disabled="disableGetCode" :class="{'disabled': disableGetCode}">{{validateText}}</el-button>
              </div>
            </el-input>
          </el-form-item>
          <el-form-item class="sureBtn">
            <el-button type="primary" style="width:100%" @click="modifyPhoneTwo('newphone')">确定</el-button>
          </el-form-item>
        </el-form>
      <!-- </template>  -->
    </el-dialog>
    <!-- 修改成功 -->
    <el-dialog :visible.sync="successVisible" width="380px" top="20vh" :show-close="false">
      <div class="successPop">
        <em class="el-icon-circle-check color-blue"></em>
        <h2>修改成功</h2>
        <el-button type="primary" class="successBtn" @click="closeSuccess">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { modifyPassword, sendCode, verifyImage, mobileValidate, modifyMobile } from '@/service/get-data'
  import { tab } from '@/components/index'
  import { Form, FormItem, Button, Dialog, Input } from 'element-ui'
  import { mapState, mapActions } from 'vuex'
  import { phoneReplace } from '@/tool/tool'
  import { PHONE } from '@/config/regex'
  export default{
    components: {
      tab,
      elForm: Form,
      elFormItem: FormItem,
      elButton: Button,
      elDialog: Dialog,
      elInput: Input
    },
    data () {
      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.modifyPwdForm.newpwd) {
          callback(new Error('您输入的新密码不一致!'))
        } else {
          callback()
        }
      }
      let validateOldPwd = (rule, value, callback) => {
        this.oldpwdError.status = false
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else {
          callback()
        }
      }
      let checkAge = (rules, value, cb) => {
        this.$store.dispatch('checkAgess', {rules, value, cb})
      }
      let checkPwd = (rules, value, cb) => {
        this.$store.dispatch('checkNewPws', {rules, value, cb})
      }
      let checkPhone = (rules, value, cb) => {
        if (!value) {
          this.phoneError.status = true
          cb(new Error('手机号码不能为空'))
          this.phoneError.status = true
        } else if (!PHONE.test(value)) {
          this.phoneError.status = true
          cb(new Error('输入正确的手机号码'))
        } else {
          this.phoneError.status = false
          cb()
        }
      }
      let checkCodeMes = (rules, value, cb) => {
        this.$store.dispatch('checkCodeMes', {rules, value, cb})
      }
      return {
        ruless: {
          age: [{required: true, trigger: 'blur', validator: checkAge}]
        },
        pwdDialogVisi: false,
        successVisible: false, // 显示成功的弹窗
        changePhoneVisi: false, // 修改手机号
        oldphoneTem: true, //  验证原始手机号码
        oldMobError: {
          status: false,
          text: ''
        },
        accountPwd: '', // 登录密码
        modifyPwdForm: {
          oldpwd: '',
          newpwd: '',
          repwd: ''
        },
        changePwdrules: {
          oldpwd: [
            { validator: validateOldPwd, trigger: 'blur' }
          ],
          newpwd: [
            {validator: checkPwd, trigger: 'blur'}
          ],
          repwd: [
            { validator: validatePass, trigger: 'blur' }
          ]
        },
        newPhoneFormrules: {
          newtel: [{ validator: checkPhone, trigger: 'change' }],
          code: [{validator: checkCodeMes, trigger: 'blur'}]
        },
        changePhoneForm: {
          code: ''
        },
        newPhoneForm: {
          newtel: '',
          code: ''
        },
        time: 0,
        changeDiaTit: '', // 手机安全验证的标题
        isSend: false, // 短信是否发送
        codeImg: '', // 图形验证码base64
        imgVerifyCode: '', // 图形验证码
        newPhoneVisi: false,
        phoneError: {
          status: true, // true 代表是错误的
          text: ''
        },
        oldpwdError: {
          status: false,
          text: ''
        },
        changeType: '' // 修改类型
      }
    },
    methods: {
      ...mapActions(['fetchWarehouseId']),
      // 修改密码后,请重新登录
      exit () {
        this.$store.commit('EXIT', true)
        this.$store.state.shopcart.cartlist = []
        this.$store.state.shopcart.shopCartId = ''
        this.$message({message: '修改密码后,请重新登录'})
        // this.fetchWarehouseId(true)
        this.$router.push({name: 'Login'})
      },
      // 关闭弹窗
      closePop (done) {
        this.modifyPwdForm.oldpwd = ''
        this.modifyPwdForm.newpwd = ''
        this.modifyPwdForm.repwd = ''
        this.oldpwdError.status = false
        done()
      },
      // 修改密码请求
      async fetchModifyPwd () {
        let res = await modifyPassword(this.modifyPwdForm.oldpwd, this.modifyPwdForm.newpwd)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this.pwdDialogVisi = false
          this.successVisible = true
        } else {
          this.oldpwdError = {
            status: true,
            text: '您输入的旧密码不正确'
          }
        }
      },
      modifyPwd (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.changeType = 'PWD'
            this.fetchModifyPwd()
          } else {
            this.$message({
              message: '请填入正确的信息'
            })
            return false
          }
        })
      },
      showChangePhoneDia () {
        this.changePhoneVisi = true
        this.changePhoneForm.code = ''
        this.newPhoneForm.code = ''
      },
      // 获取图形验证码
      async verifyImage () {
        let res = await verifyImage()
        if (res.status === 200) {
          var windowUrl = window.URL || window.webkitURL // 处理浏览器兼容性
          this.codeImg = windowUrl.createObjectURL(res.data)
        }
      },
      // 发送短信验证码
      async getCode (phoneNum, type) {
        // this.time = 60
        if (this.time !== 0) {
          return
        }
        let res = await sendCode(phoneNum, type, this.imgVerifyCode)
        if (res.data.resultCode && res.data.resultCode !== 2000) {
          this.verifyImage() // 重新获取验证码
          this.$message({
            message: res.data.resultMsg,
            type: 'error'
          })
        } else {
          this.time = 60
        }
      },
      // 手机验证接口
      async mobileValidate (mobile, type, code) {
        let res = await mobileValidate(mobile, type, code)
        return res
      },
      // 验证旧手机号码
      modifyPhoneOne () {
        this.changeType = 'MOBILD'
        let _code = this.changePhoneForm.code
        if (!_code || _code.length !== 6) {
          this.oldMobError = {
            status: true,
            text: '请填写正确验证码'
          }
          return
        }
        this.mobileValidate(this.mobile, 0, this.changePhoneForm.code).then((res, rej) => {
          this.oldMobError.status = false
          if (res.data.resultCode === 2000) {
            this.time = 0
            this.newPhoneVisi = true
            this.changePhoneVisi = false
            this.isSend = false
            // console.log(this.isSend)
          } else {
            this.oldMobError = {
              status: true,
              text: '请填写正确验证码'
            }
            this.$message({
              message: '请填入正确的验证码'
            })
          }
        })
      },
      // 修改手机号接口,换成新手机号
      async modifyMobile () {
        let res = await modifyMobile(this.newPhoneForm.newtel, this.newPhoneForm.code)
        return res
      },
      // 验证新手机号码
      modifyPhoneTwo (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.modifyMobile().then((res, rej) => {
              if (res.data.resultCode === 2000) {
                this.newPhoneVisi = false
                this.successVisible = true
                this.$store.dispatch('getUserData')
                this.time = 0
                this.changePhoneForm.code = ''
                this.isSend = false
              } else {
                this.$message({
                  message: '请填入正确的验证码'
                })
              }
            })
          } else {
            this.$message({
              message: '请填入正确的信息'
            })
            return false
          }
        })
      },
      // 关闭成功弹窗
      closeSuccess () {
        if (this.changeType === 'PWD') {
          this.successVisible = false
          this.exit() // 修改密码后,重新登录
        } else {
          this.successVisible = false
        }
      }
    },
    mounted () {
      this.verifyImage()
      // this.fetchLogin()
    },
    computed: {
      validateText () {
        return this.time > 0 ? '重新发送' + this.time + 's' : '发送验证码'
      },
      ...mapState({
        mobile: state => {
          return state.user.mobile
        }
      }),
      disableGetCode () {
        return (this.isSend || this.phoneError.status) && this.imgVerifyCode
      }
    },
    watch: {
      time (newV) {
        let t
        if (newV <= 0) {
          clearTimeout(t)
          this.time = 0
          this.isSend = false
        } else {
          this.isSend = true
          t = setTimeout(() => {
            this.time--
          }, 1000)
        }
      }
    },
    filters: {
      phoneReplace
    }
  }
</script>
<style lang="scss" scoped>
  .safe_cont{
    border: 1px solid #ECECEC;
    border-radius: 2px;
  }
  .safe_item{
    display: table;
    padding: 30px 8% 30px 5%;
    width: 87%;
    @include border_bt(#ECECEC);
    &>div{
      display:table-cell;
      vertical-align: middle;
    }
    &:last-child{
      border-bottom: none;
    }
  }
  .safe_img{
    width: 45px;
    height: 45px;
    color: #999999;
    border-radius:50%;
    text-align: center;
    line-height: 45px;
    border: 2px solid #999999;
  }
  .iconsize{
    font-size: 28px;
    vertical-align: middle;
  }
  .safe_infos{
    padding-left:18px;
    color: #666666;
    line-height: 23px;
    h2{
      font-size: 18px;
      color: #333333;
      line-height: 25px;
      margin-bottom: 5px;
    }
    h3{
      font-size: 14px;
      line-height: 20px;
    }
  }
  // .color-blue{
  //   color:#2A91D2;
  // }
  .el-form-item{
    margin-bottom:5px!important;
  }
  .successPop{
    text-align: center;
    color:#333333;
    font-size: 20px;
    line-height: 30px;
    margin-bottom: 30px;
    em{font-size: 60px;}
    .successBtn{
      width:80%;
      margin-top:25px;
    }
  }
  .valiCode{
    width: 74px;
    text-align: center;
    padding: 5px 4px;
    color:#2A91D2;
    & > .disabled {
      color:#666666
    }
  }
  .sureBtn{
    margin-top: 20px;
  }
  // .error{
  //   display: none;
  //   color: #FF7300;
  //   font-size: 12px;
  //   line-height: 1;
  //   padding-top: 4px;
  //   position: absolute;
  //   top: 100%;
  //   left: 0;
  // }
  // .error.errorBlock{
  //   display: block;
  // }
  .error{
    color: #FF7300;
    font-size: 12px;
    line-height: 1.5;
    border: 1px solid #ff7300;
    border-radius: 2px;
    padding-left: 2px;
  }
</style>

